package com.memoryangelapplication.deviceinfo;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.memoryangelapplication.services.GPSTracker;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.util.Log;

public class MemoryAngelDeviceInfo extends Service // implements
													// LocationListener {
{
	// private LocationManager lm;
	// List list;
	Context context;

	private String currentDate;
	private int hours;
	private String newhours;
	private int minute;
	String newminute;
	private String current_time;
	LocationManager locManager;
	LocationListener locListener;
	Location mobileLocation;

	LocationManager locationManager;
	BroadcastReceiver batteryReceiver;

	Handler handler;
	Runnable r;
	Date date;
	// private SimpleDateFormat sdf;
	static String agps_time;

	// all static values;
	public static int currentVolume = 0;
	public static String deviceid = null;
	public static String text, agps_to_log;
	public static double lat, longi = 0;
	public static int batterylevel = 0;
	public static String datetime = null;
	Location location = null;

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();

		locationManager = (LocationManager) this
				.getSystemService(LOCATION_SERVICE); // <2>
		location = locationManager
				.getLastKnownLocation(LocationManager.GPS_PROVIDER); // <5>

		handler = new Handler();

		context = MemoryAngelDeviceInfo.this;
		TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

		deviceid = getDeviceID(telephonyManager);

		deviceInfo();

		/*
		 * if (mobileLocation != null) { locManager.removeUpdates(locListener);
		 * // This needs to stop getting the location data and save the battery
		 * power.
		 * 
		 * String londitude = "Londitude: " + mobileLocation.getLongitude();
		 * String latitude = "Latitude: " + mobileLocation.getLatitude(); String
		 * altitiude = "Altitiude: " + mobileLocation.getAltitude(); String
		 * accuracy = "Accuracy: " + mobileLocation.getAccuracy(); String time =
		 * "Time: " + mobileLocation.getTime();
		 * 
		 * 
		 * 
		 * }
		 */

	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);

		// <7>

		r = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub

				// values = text;
				AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
				MemoryAngelDeviceInfo.currentVolume = audio
						.getStreamVolume(AudioManager.STREAM_RING);

				Log.e("device ringing volume is", "" + currentVolume
						+ "device id is" + deviceid);

				locationManager.requestLocationUpdates(
						LocationManager.GPS_PROVIDER, 300000, 1L,
						new LocationListener() {

							/*
							 * if (location != null) { Log.d("",
							 * location.toString());
							 * this.onLocationChanged(location); }
							 */

							@Override
							public void onStatusChanged(String provider,
									int status, Bundle extras) {
								// TODO Auto-generated method stub

							}

							@Override
							public void onProviderEnabled(String provider) {
								// TODO Auto-generated method stub

							}

							@Override
							public void onProviderDisabled(String provider) {
								// TODO Auto-generated method stub

							}

							@Override
							public void onLocationChanged(Location location) {
								// TODO Auto-generated method stub
								text = String
										.format(" \n "
												+ "\n"
												+ "Lat:\t %f\nLong:\t %f\nAlt:\t %f\nBearing:\t %f",
												location.getLatitude(),
												location.getLongitude(),
												location.getAltitude(),
												location.getBearing());
								agps_to_log = "Lat" + location.getLatitude()
										+ "," + "Long"
										+ location.getLongitude() + "," + "Alt"
										+ location.getAltitude() + ","
										+ "Bearing" + location.getBearing();
								GPSTracker gps = new GPSTracker(context);

								if (gps.canGetLocation()) {

									lat = gps.getLatitude();
									longi = gps.getLongitude();

								} else {
									// can't get location
									// GPS or Network is not enabled
									// Ask user to enable GPS/network in
									// settings
									gps.showSettingsAlert();
								}

								/*
								 * lat = location.getLatitude(); longi =
								 * location.getLongitude();
								 */

								Calendar calendar = Calendar.getInstance();
								SimpleDateFormat sdf = new SimpleDateFormat(
										"yyyy-MM-dd");
								currentDate = sdf.format(calendar.getTime());

								Date dt = new Date();

								hours = dt.getHours();
								newhours = "" + hours;
								// Toast.makeText(getApplicationContext(),
								// "current hour is"+newhours,2000).show();

								if (hours < 10) {
									newhours = "0" + hours;

								}
								minute = dt.getMinutes();
								newminute = "" + minute;

								if (minute < 10) {

									newminute = "0" + minute;

								}

								current_time = newhours + ":" + minute + ":00";

								datetime = currentDate + "%20" + current_time;

								// this.locationText.setText(text);
								// Toast.makeText(DeviceInformation.this,
								// "values are:"+text+"current time and dat are"+currentDate+" "+current_time,
								// Toast.LENGTH_LONG).show();

							}
						});

				handler.postDelayed(r, 300000);

			}

		};
		handler.postDelayed(r, 10);
		// values = "";

	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();

		handler.removeCallbacks(r);
		try {

			if (batteryReceiver != null) {

				unregisterReceiver(batteryReceiver);

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/*
	 * @Override public void onLocationChanged(Location location) { // TODO
	 * Auto-generated method stub // agps_values(); Log.d("",
	 * "onLocationChanged with location " + location.toString()); text =
	 * String.format
	 * (" \n "+"\n"+"Lat:\t %f\nLong:\t %f\nAlt:\t %f\nBearing:\t %f",
	 * location.getLatitude(), location.getLongitude(), location.getAltitude(),
	 * location.getBearing()); agps_to_log = "Lat"+
	 * location.getLatitude()+","+"Long"+location.getLongitude()
	 * +","+"Alt"+location.getAltitude()+","+"Bearing"+location.getBearing();
	 * 
	 * 
	 * lat = location.getLatitude(); longi = location.getLongitude();
	 * 
	 * 
	 * Calendar calendar = Calendar.getInstance(); SimpleDateFormat sdf = new
	 * SimpleDateFormat("yyyy-MM-dd"); currentDate =
	 * sdf.format(calendar.getTime());
	 * 
	 * Date dt = new Date();
	 * 
	 * hours = dt.getHours(); newhours = ""+hours;
	 * //Toast.makeText(getApplicationContext(),
	 * "current hour is"+newhours,2000).show();
	 * 
	 * if (hours<10) { newhours = "0"+hours;
	 * 
	 * } minute = dt.getMinutes(); newminute = ""+minute;
	 * 
	 * if (minute<10) {
	 * 
	 * newminute = "0"+minute;
	 * 
	 * }
	 * 
	 * current_time =newhours+":"+minute+":00";
	 * 
	 * datetime = currentDate+"%20"+current_time;
	 * 
	 * // this.locationText.setText(text); Toast.makeText(this,
	 * "values are:"+text
	 * +"current time and dat are"+currentDate+" "+current_time,
	 * Toast.LENGTH_LONG).show(); Log.e("location values are",
	 * "location"+text+"date"+currentDate+""+current_time);
	 * 
	 * }
	 * 
	 * @Override public void onProviderDisabled(String provider) { // TODO
	 * Auto-generated method stub
	 * 
	 * }
	 * 
	 * @Override public void onProviderEnabled(String provider) { // TODO
	 * Auto-generated method stub
	 * 
	 * }
	 * 
	 * @Override public void onStatusChanged(String provider, int status, Bundle
	 * extras) { // TODO Auto-generated method stub
	 * 
	 * }
	 */

	// retrieve a reference to an instance of TelephonyManager

	//

	public static String getDeviceID(TelephonyManager phonyManager) {

		String id = phonyManager.getDeviceId();
		if (id == null) {
			id = "not available";
		}

		int phoneType = phonyManager.getPhoneType();
		switch (phoneType) {
		case TelephonyManager.PHONE_TYPE_NONE:
			return "NONE:" + id;

		case TelephonyManager.PHONE_TYPE_GSM:
			return "GSM:IMEI=" + id;

		case TelephonyManager.PHONE_TYPE_CDMA:
			return "CDMA:MEID/ESN=" + id;

			/*
			 * for API Level 11 or above case TelephonyManager.PHONE_TYPE_SIP:
			 * return "SIP";
			 */

		default:
			return "UNKNOWN:ID=" + id;
		}
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	public void deviceInfo() {

		BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
			int scale = -1;
			int level = -1;
			int voltage = -1;
			int temp = -1;

			@Override
			public void onReceive(Context context, Intent intent) {
				level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
				scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
				temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
				voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);

				batterylevel = level;
			}
		};
		IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
		try {
			registerReceiver(batteryReceiver, filter);
		} catch (Exception e)

		{
			e.printStackTrace();
		}
	}

}
